package com.yhm.testSpringMvc.Thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionTestClass {

    boolean isSubExec = true;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void sub(int i) {
        lock.lock();
        try {
            while (!isSubExec) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (isSubExec == true) {
                for (int j = 0; j < 10; j++) {
                    System.out.println("子线程第" + i + "次循环" + j);
                }
                isSubExec = false;
            }
            condition.signal();
        } finally {
            lock.unlock();
        }

    }

    public void main(int i) {
        lock.lock();
        try {
            while (isSubExec) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (isSubExec == false) {
                for (int j = 0; j < 100; j++) {
                    System.out.println("主main线程第" + i + "次循环" + j);
                }
                isSubExec = true;
            }
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
}